<template>
  <div class="login">
    <!-- 登录页面 -->
    <el-form :model="form" :rules="rules" ref="form" label-width="80px" status-icon>
      <img src="../assets/头像.jpg" alt />
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密 码" prop="password">
        <el-input @keyup.enter.native ="onSubmit" type="password" v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button class="btnLogin" type="primary" @click="onSubmit">登录</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      // 表单验证
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change']
          },
          {
            min: 3,
            max: 12,
            message: '用户名必须是3~12的字符',
            trigger: ['blur', 'change']
          }
        ],
        // 验证密码
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['blur', 'change']
          },
          {
            min: 3,
            max: 12,
            message: '密码必须是3~12的字符',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  methods: {
    // 登录
    async onSubmit () {
      // console.log(this.$refs)
      // 验证表单
      try {
        await this.$refs.form.validate()
        // 当执行到这一步说明校验成功
        const { meta, data } = await this.$axios.post('login', this.form)
        if (meta.status === 200) {
          this.$message({
            message: meta.msg,
            type: 'success',
            center: true,
            duration: 1000
          })
          localStorage.setItem('token', data.token)
          // 跳转到首页
          this.$router.push('index')
        // this.$router.push({ name: 'index' })
        } else {
          this.$message({
            message: meta.msg,
            type: 'error',
            center: true,
            duration: 1000
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 重置
    onReset () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  background-color: #2d434c;
  position: relative;
}
.el-form {
  width: 400px;
  padding: 20px;
  padding-top: 80px;
  background: #ffffff;
  border-radius: 20px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  img {
    width: 130px;
    height: 130px;
    border-radius: 50%;
    border: 4px solid #ffffff;
    position: absolute;
    top: -80px;
    left: 50%;

    transform: translateX(-50%);
  }
  .btnLogin {
    margin-right: 80px;
  }
}
</style>
